package com.linkdood.app.config;

import com.linkdood.app.domain.ScheduleTask;
import com.linkdood.app.enums.TaskStatusEnum;
import com.linkdood.app.service.ScheduleTaskService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;


/**
 * 启动时自动加载所有定时任务
 *
 * @author hycao
 */
@Configuration
@ConditionalOnExpression("'${org.quartz.enabled}'=='true'")
public class QuartzConfiguration {

    private final ScheduleTaskService scheduleTaskService;

    public QuartzConfiguration(ScheduleTaskService scheduleTaskService) {
        this.scheduleTaskService = scheduleTaskService;
    }

    /**
     * 每次启动时加载现有的所有定时任务
     */
    @Bean
    public void cronTaskJob() {
        List<ScheduleTask> scheduleTaskList = scheduleTaskService.list();

        // 按照数据库状态启动任务
        scheduleTaskList.stream().filter(scheduleTask ->
                TaskStatusEnum.START.equals(scheduleTask.getJobStatus())
        ).forEach(scheduleTaskService::startTask);
    }

}
